package com.ucode.cgms.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import com.ucode.cgms.mapper.CgmsCompanionOrderMapper;
import com.ucode.cgms.mapper.CgmsJointServiceUserMapper;
import com.ucode.cgms.service.CgmsJointServiceUserService;
import com.ucode.model.cgms.CgmsCompanionOrder;
import com.ucode.model.cgms.CgmsJointServiceUser;
import com.ucode.model.cgms.enums.CgmsCompanionOrderStatusEnum;
import com.ucode.model.cgms.enums.CgmsSysResultCodeEnum;
import com.ucode.tool.base.enums.GlobalResultCodeEnum;
import com.ucode.tool.exception.UcodeServiceException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Service
public class CgmsJointServiceUserServiceImpl implements CgmsJointServiceUserService {

    @Resource
    private CgmsJointServiceUserMapper cgmsJointServiceUserMapper;
    @Resource
    private CgmsCompanionOrderMapper cgmsCompanionOrderMapper;

    @Override
    public CgmsJointServiceUserMapper initMapper() {
        return cgmsJointServiceUserMapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(CgmsJointServiceUser cgmsJointServiceUser) {
        List<CgmsJointServiceUser> list = cgmsJointServiceUserMapper.queryListByOrderId(cgmsJointServiceUser.getOrderId());
        if(CollUtil.isEmpty(list))
            return 0;
        CgmsJointServiceUser dbBean = null;

        List<CgmsJointServiceUser> newLiist = new ArrayList<>();

        for(CgmsJointServiceUser bean : list){
            if(ObjUtil.equals(bean.getId(), cgmsJointServiceUser.getId())){
                dbBean = bean;
            }else {
                newLiist.add(bean);
            }
        }
        if(ObjUtil.isNull(dbBean))
            return 0;
        dbBean.setAmount(cgmsJointServiceUser.getAmount());
        dbBean.setServiceUserId(null);
        dbBean.setOrderId(null);
        newLiist.add(dbBean);

        CgmsCompanionOrder companionOrder = cgmsCompanionOrderMapper.selectByPrimaryKey(cgmsJointServiceUser.getOrderId());
        if(ObjUtil.isNull(companionOrder)){
            throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_ORDER_NOT_EXISTS);
        }
        //验证分账总金额不能大于总订单金额
        BigDecimal totalAmount = newLiist.stream().map(CgmsJointServiceUser::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        if(totalAmount.compareTo(companionOrder.getPayPrice()) > 0){
            throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_ORDER_SUB_AMOUNT_IS_MORE_THAN_PAY_PRICE);
        }

        return cgmsJointServiceUserMapper.update(cgmsJointServiceUser);
    }

    @Override
    public List<CgmsJointServiceUser> queryListByOrderId(Long orderId) {
        return cgmsJointServiceUserMapper.queryListByOrderId(orderId);
    }

    @Override
    public CgmsJointServiceUser queryOne(Long orderId, Long serviceUserId) {
        return cgmsJointServiceUserMapper.queryOne(orderId, serviceUserId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delete(Long userId, Long id) {
        CgmsJointServiceUser cgmsJointServiceUser = cgmsJointServiceUserMapper.selectByPrimaryKey(id);
        if(ObjUtil.isNotNull(cgmsJointServiceUser)){
            CgmsCompanionOrder companionOrder = cgmsCompanionOrderMapper.selectByPrimaryKey(cgmsJointServiceUser.getOrderId());
            if(ObjUtil.isNull(companionOrder)){
                throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_ORDER_NOT_EXISTS);
            }

            //校验接单状态
            if(!ObjUtil.equals(companionOrder.getStatus(), CgmsCompanionOrderStatusEnum.IN_SERVICE.getCode())){
                throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_ORDER_STATUS_IS_NOT_IN_SERVICE);
            }

            //校验接单用户
            if(!ObjUtil.equals(companionOrder.getServiceUserId(),userId)){
                throw new UcodeServiceException(GlobalResultCodeEnum.VALIDATE_FAILED);
            }


            Set<Long> jointServiceUserIds = ObjUtil.isNotEmpty(companionOrder.getJointServiceUserIds()) ? companionOrder.getJointServiceUserIds() : new HashSet<>();
            jointServiceUserIds.remove(cgmsJointServiceUser.getServiceUserId());
            CgmsCompanionOrder updateBean = new CgmsCompanionOrder();
            updateBean.setId(cgmsJointServiceUser.getOrderId());
            updateBean.setJointServiceUserIds(jointServiceUserIds);
            cgmsCompanionOrderMapper.update(updateBean);

            return cgmsJointServiceUserMapper.deleteByPrimaryKey(id);
        }
        return 0;
    }

}
